<?php

namespace app\api\service;

use app\lib\exception\TokenException;
use think\Cache;
use think\Controller;
use think\Exception;
use think\Request;

class Token extends Controller
{

    // 生成令牌
    public static function generateToken()
    {
//        隨機字符串
        $randChar = getRandChar(32);
        $timestamp = $_SERVER['REQUEST_TIME_FLOAT'];
//
        $tokenSalt = config('secure.token_salt');
        return md5($randChar . $timestamp . $tokenSalt);
    }


    //验证token是否合法或者是否过期
    //验证器验证只是token验证的一种方式
    //另外一种方式是使用行为拦截token，根本不让非法token
    //进入控制器
    public static function isHasToken()
    {
        $token = Request::instance()->header('token');
        if (empty($token)){
            throw new TokenException();
        }
        $servicetoken = Cache::store('redis')->get($token);
        if(!$token==$servicetoken){
            throw new TokenException();
        }
        return true;
    }




//    public static function needPrimaryScope()
//    {
//        $scope = self::getCurrentTokenVar('scope');
//        if ($scope) {
//            if ($scope >= ScopeEnum::User) {
//                return true;
//            }
//            else{
//                throw new ForbiddenException();
//            }
//        } else {
//            throw new TokenException();
//        }
//    }
//
    // 封装通过token 获取用户id
    public static function getCurrentTokenVar($key)
    {
        $token = Request::instance()->header('token');
        $vars = Cache::store('redis')->get($token);
        if (!$vars) {
            throw new TokenException();
        } else {
            if(!is_array($vars))
            {
                $vars = json_decode($vars, true);
            }
            if (array_key_exists($key, $vars)) {
                return $vars[$key];
            }else{
                throw new Exception('尝试获取的Token变量并不存在');
            }
        }
    }

}